import { defineStore } from 'pinia'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),

  getters: {
    isLoggedIn: state => !!state.token
  },

  actions: {
    setToken(token) {
      this.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },

    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    login({ token, admin }) {
      if (token) {
        this.setToken(token)
        this.setUserInfo(admin)
      }
    },

    logout() {
      this.setToken('')
      this.userInfo = null
      router.push('/admin/login')
    }
  }
})
